#include "win32thread.h"

DWORD WINAPI ThreadFunc(LPVOID pt)
{
	CXWinThread* pthread = (CXWinThread*)pt;
    while(!pthread->_close)
	{
		SetEvent(pthread->_hevent);
		do
		{
			pthread->_task = pthread->_mgr->GetTask();
			if(pthread->_task != NULL)
			{
				pthread->_task->Execute();
				delete pthread->_task;
			}
		}while(pthread->_task != NULL);
		ReleaseMutex(pthread->_hmutex);
		pthread->_task = NULL;
		WaitForSingleObject(pthread->_hmutex,INFINITE);
	}
	return 0;
}

CXWinThread::CXWinThread(ITaskMgr* taskmgr, HANDLE mutex, HANDLE hevent):
	_mgr(taskmgr), _hmutex(mutex), _hevent(hevent)
{
    _close = false;
    _task = NULL;
	_hthread = CreateThread(NULL,0,ThreadFunc,(LPVOID)this,0,NULL);
}

CXWinThread::~CXWinThread()
{
	Close();
	if(_task != NULL)
    {
        delete _task;
        _task = NULL;
    }
	ReleaseMutex(_hmutex);
	CloseHandle(_hthread);
}


void CXWinThread::Close()
{
    _close = true;
}